# coding=utf-8
import collections

from django.http import HttpResponse
from raven.utils import json

from blog.models import JSONBaseMixin


class JSONHttpResponse(HttpResponse):

    def __init__(self, json=None, *args, **kwargs):
        super(JSONHttpResponse, self).__init__(*args, **kwargs)
        self.json = json


def getResult(success, message, result=None, status_code=0, dialog=0, jifen=None, p_index=None, p_count=None,
              total_count=None):
    """
    0 正常返回 code
    1 登录过期，需要重新登录
    2 项目id错误
    3 需要提供用户名和密码
    4 error
    5 用户禁止使用
    6 用户离开了当前组织
    7 组织余额不足，需要充值后继续使用
    8 权限不足
    9 手机号校验

    dialog 客户端提示类型
    0： 红字 3秒 提示
    1：Alert 提示
    by:王健 at:2015-1-3
    返回值，加上content-type = json
    by:王健 at:2015-1-6
    优化返回结构的 status_code
    by:王健 at:2015-1-10
    增加手机号没有校验的提示
    by:王健 at:2015-1-15
    增加积分
    by:王健 at:2015-2-5
    继承HttpResponse 添加json属性
    by:王健 at:2015-08-24
    """
    message = message or ""
    map = {'success': success, 'message': message, 'status_code': status_code, 'dialog': dialog}
    if result:
        map['result'] = MyEncoder.default(result)
    if not success and status_code == 0:
        map['status_code'] = 4
    # if jifen and jifen[0]:
    #     map['jifen'] = jifen[1]
    #     map['jifen_msg'] = jifen[2]
    if p_index != None and p_count != None:
        map['p_index'] = p_index
        map['p_count'] = p_count
    if total_count:
        map['total_count'] = total_count
    jsonstr = json.dumps(map)
    return JSONHttpResponse(content=jsonstr, json=map, content_type=u'application/json')


class MyEncoder():
    @staticmethod
    def default(obj):
        """
        优化Model 序列化 功能
        by:王健 at:2015-1-29
        优化 序列化算法
        by:王健 at:2015-3-9
        修改序列化算法
        by: 范俊伟 at:2015-08-24
        :param obj:
        :return:
        """
        if isinstance(obj, dict):
            return obj
        if isinstance(obj, collections.Iterable):
            l = []
            for o in obj:
                if isinstance(o, JSONBaseMixin):
                    l.append(o.toJSON())
                elif hasattr(o,'toJSON'):
                    l.append(o.toJSON())
                else:
                    l.append(o)
            return l
        if isinstance(obj, JSONBaseMixin):
            return obj.toJSON()

        return None


def post_to_method_parmes(parms):
    """
    post参数转函数参数
    by: 李艳军 at:2017-007-19
    :return:
    """

    def post_to_method_parmes_func(func=None):
        def test(request, *args, **kwargs):
            for i in parms:
                kwargs[i] = request.REQUEST.get(i)
            return func(request, *args, **kwargs)

        return test
    return post_to_method_parmes_func

from django.http.response import HttpResponse
import hashlib
from django.views.decorators.csrf import csrf_exempt


@csrf_exempt
def check_signature(request):
    if request.method == 'GET':
        signature = request.GET.get('signature')
        timestamp = request.GET.get('timestamp')
        nonce = request.GET.get('nonce')
        echostr = request.GET.get('echostr')
        token = 'leartd'

        hashlist = [token, timestamp, nonce]
        hashlist.sort()
        print('[token, timestamp, nonce]', hashlist)
        hashstr = ''.join([s for s in hashlist]).encode('utf-8')
        print('hashstr befor sha1', hashstr)
        hashstr = hashlib.sha1(hashstr).hexdigest()
        print('hashstr sha1', hashstr)
        if hashstr ==signature:
            return HttpResponse(echostr)
        else:
            return HttpResponse('error')
    else:
        return HttpResponse('chenggong')